package demo;

import com.google.common.collect.Lists;
import ru.nsu.fit.iconveyor.conveyor.node.InputNode;
import ru.nsu.fit.iconveyor.conveyor.node.NodeConnection;

import java.util.*;

/**
 * This class read file names from properties and send it to channel.
 *
 * @author Timur Zolotuhin (tzolotuhin@gmail.com)
 */
public class InputPictureNode extends InputNode {
    public static final String OUTPUT_RESULT = "result";

    private static final String FILE_NAMES_DELIMITER = "\\|";

    // Define
    public final static String INPUT_FILE_NAMES = "input_file_names";

    // Main data
    boolean executed = false;

    private final Object generalMutex = new Object();

    private final NodeConnection<ArrayList> outputResult;

    public InputPictureNode(String id) {
        super(id);

        outputResult = new NodeConnection<ArrayList>(ArrayList.class, NodeConnection.Type.OUTPUT, OUTPUT_RESULT);
        addNodeConnection(outputResult);
    }

    @Override
    public Map<String, Object> execute(Map<String, Object> resource, Properties prop) {
        String fileNamesString = getParameter(INPUT_FILE_NAMES);
        Collection<String> fileNames = Lists.newArrayList(fileNamesString.split(FILE_NAMES_DELIMITER));

        // Generate result
        Map<String, Object> bundles = new HashMap<String, Object>();
        bundles.put(outputResult.getName(), fileNames);
        return bundles;
    }

    @Override
    public Map<String, Object> preExecute(Map<String, Object> availableInputResource, Properties prop) {
        synchronized (this) {
            if(executed) {
                return null;
            } else {
                // contract that method 'execute' will called
                executed = true;
                return availableInputResource;
            }
        }
    }
}
